<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use think\Db;

class RunsendmailaController extends HomeBaseController
{
	public function searchupdatemail()
	{
		//更新订单的邮件
		$Separator = isset($_GET['webtest'])? "<br>" : "\n\r";
		$Separator = '		'.date("Y-m-d H:i").'	'.$Separator;
		$webmailList = Db::name('webmail')->field('websitename,emailname')->select();
		$webmailArr = $webmailArrKey = array();
		foreach($webmailList as $k => $v) {
			$key = explode('.', $v['websitename']);
			$key = $key[1];
			$webmailArrKey[] = $key;
			$webmailArr[$key] = $v['emailname'];
		}
		$orderList = Db::name('order')->where("websitemail='未找到'")->field('id,websitemail,status,logwebsite')->select();
		// var_dump($orderList);
		foreach ($orderList as $k => $v) {
			$webSiteArr = explode('-', $v['logwebsite']);
			if(count($webSiteArr) == 4){
				$websiteName = $webSiteArr[0];
			}elseif(count($webSiteArr) == 5){
				$websiteName = $webSiteArr[0].'-'.$webSiteArr[1];
			}
			$websiteName = str_replace('爆品', '', $websiteName);
			if(in_array($websiteName, $webmailArrKey)){
				$website = $webmailArr[$websiteName];
			}else{
				$website = '未找到';
			}

			$data['id'] = $v['id'];
			$data['websitemail'] = $website;
			$result = DB::name('order')->update($data);
			if($result){
				echo "ID 为 ".$v['id']."		站点名称为 ".$v['logwebsite']." 	已经匹配成功支持邮箱 ".$website.$Separator;
			}else{
				echo "ID 为 ".$v['id']."		站点名称为 ".$v['logwebsite']." 	没有找到对应的支持邮箱，请联系 ".$v['logwebsite']." 对应的站长 $Separator";
			}
		}
		exit;
	}

	public function sendmail(){
		$Separator = isset($_GET['s'])? "<br>" : "\n\r";
		$Separator = '		'.date("Y-m-d H:i").'	'.$Separator;
		//获取没有发送的数据
		$id = $_GET['id'];
		$orderList = Db::name('order') ->where("id = $id") ->select();
		if(!$orderList[0]['useremail'] || !$orderList[0]['username'] || !$orderList[0]['logsendway'] || !$orderList[0]['websitemail']){
			$updateInfo['id'] 			= $orderList[0]['id'];
			$updateInfo['sendstatus'] 	= 101;
			$result = DB::name('order')->update($updateInfo);
			echo '发送失败	当前订单号id为	'.$updateInfo['id'].' 的订单必要信息不全'.$Separator;
			exit;
		}
		
		$sendArr = $orderList[0];
		$mailList = Db::name('webmail') ->field('emailname,emailpawd') ->where(["emailname" => $sendArr['websitemail']])->select();
		if(@!count($mailList[0])){
			$updateInfo['id'] 			= $sendArr['id'];
			$updateInfo['sendstatus'] 	= 102;
			echo '发送失败	当前订单号id为	'.$updateInfo['id'].' 没有匹配到对应的邮箱'.$Separator;
			exit;
		}else{
			if(@!$mailList[0]['emailpawd']){
				$updateInfo['id'] 			= $sendArr['id'];
				$updateInfo['sendstatus'] 	= 103;
				echo '发送失败	当前订单号id为	'.$updateInfo['id'].' 没有匹配到对应的邮箱密码'.$Separator;
				exit;
			}
			$sendArr['emailpawd'] = $mailList[0]['emailpawd'];
		}

		
		//发送邮件
		if($sendArr){
			$sendFrom = $sendArr['websitemail'];;
                        $sendEmail = 'AKIAI3IYFRCB72F3P3GA';
                        $sendPwd = 'AiMEv9gVTwAGoL5ea3nUzXuZ/+NY0RCLT6PdRxsLWUb/';

			//$data['to']		=	'496042513@qq.com';
			$data['to']		=	$sendArr['useremail'];
			$data['subject']=	'Order Notification';
			$data['content']=	"Dear {$sendArr['username']}:<br>The products you ordered have been shipped, please check the logistics progress here.<br>Track url:https://www.trackingmore.com/china-ems-tracking.html?number={$sendArr['logsendway']}<br><br>If not found, please enter your logistic tracking number in the following address. <br>Your logistic tracking number is:  {$sendArr['logsendway']}  <br><br>Other Track url:<br> No1: http://track.yw56.com.cn/en-US/ <br>No2:http://www.yuntrack.com/Track/Detail/{$sendArr['logsendway']} <br>No3: http://track.4px.com/?locale=en_US <br><br>Have a good day~";

			 $smtpSetting['from'] 		= $sendFrom;
			 $smtpSetting['username'] 	= $sendEmail;
			 $smtpSetting['password'] 	= $sendPwd;
			#$smtpSetting['from'] 		= $sendArr['websitemail'];
			#$smtpSetting['username'] 	= $sendArr['websitemail'];
			#$smtpSetting['password'] 	= $sendArr['emailpawd'];
			$smtpSetting['from_name']	= 'Order Notification';
			$smtpSetting['host']            = 'email-smtp.us-west-2.amazonaws.com';
			$smtpSetting['smtp_secure'] = 'ssl';
			$smtpSetting['port'] 		= '465';
			$result = $this->sendData($data['to'], $data['subject'], $data['content'], $smtpSetting);
			if ($result && empty($result['error'])) {
				$updateInfo['id'] = $sendArr['id'];
				$updateInfo['status'] = 1;
				$updateInfo['sendstatus'] 	= 200;
				$updateInfo['sendmail'] 	= $sendEmail;
				$updateInfo['sendmailpwd'] 	= $sendPwd;
				$result = DB::name('order')->update($updateInfo);
				echo "发送成功	当前订单号id为	".$sendArr['id'].$Separator;exit;
			} else {
				$updateInfo['id'] = $sendArr['id'];
				$updateInfo['sendstatus'] 	= 104;
				$results = DB::name('order')->update($updateInfo);
				echo "发送失败	当前订单号id为	".$sendArr['id'].",	站长信息为 ".$sendArr['logwebsite']." 支持邮箱账号密码有误	".$result['message'].$Separator;exit;
			}
		}else{
			$updateInfo['id'] = $sendArr['id'];
			$updateInfo['sendstatus'] 	= 105;
			echo "发送失败	当前订单号id为	".$sendArr['id']." 发送邮件中的数据有误$Separator";exit;
		}
	}

	public function sendData($address, $subject, $message, $smtpSetting)
	{
	    $smtpSetting = $smtpSetting;
	    $mail        = new \PHPMailer();
	    // 设置PHPMailer使用SMTP服务器发送Email
	    $mail->IsSMTP();
	    $mail->IsHTML(true);
	    //$mail->SMTPDebug = 3;
	    // 设置邮件的字符编码，若不指定，则为'UTF-8'
	    $mail->CharSet = 'UTF-8';
	    // 添加收件人地址，可以多次使用来添加多个收件人
	    $mail->AddAddress($address);
	    // 设置邮件正文
	    $mail->Body = $message;
	    // 设置邮件头的From字段。
	    $mail->From = $smtpSetting['from'];
	    // 设置发件人名字
	    $mail->FromName = $smtpSetting['from_name'];
	    // 设置邮件标题
	    $mail->Subject = $subject;
	    // 设置SMTP服务器。
	    $mail->Host = $smtpSetting['host'];
	    //by Rainfer
	    // 设置SMTPSecure。
	    $Secure           = $smtpSetting['smtp_secure'];
	    $mail->SMTPSecure = empty($Secure) ? '' : $Secure;
	    // 设置SMTP服务器端口。
	    $port       = $smtpSetting['port'];
	    $mail->Port = empty($port) ? "25" : $port;
	    // 设置为"需要验证"
	    $mail->SMTPAuth    = true;
	    $mail->SMTPAutoTLS = false;
	    $mail->Timeout     = 10;
	    // 设置用户名和密码。
	    $mail->Username = $smtpSetting['username'];
	    $mail->Password = $smtpSetting['password'];
	    // 发送邮件。
	    if (!$mail->Send()) {
	        $mailError = $mail->ErrorInfo;
	        return ["error" => 1, "message" => $mailError];
	    } else {
	        return ["error" => 0, "message" => "success"];
	    }
	}
}
